module.exports = app => {
	const express = require('express')
	const jwt = require('jsonwebtoken')
	const AdminUser = require('../../models/AdminUser')
	const Counter = require('../../models/Counter')
	const assert = require('http-assert')
	const bcrypt = require('bcrypt')
	const qnconfig = require('../../plugins/qiniu')
	const router = express.Router({
		mergeParse: true
	})
	// 接口
	//新建分类
	router.post('/', async (req, res) => {
		// 创建该模型，并填入post中传递过来的数据。
		const Model = await req.Model.create(req.body)
		// 将创建后的模型数据返回到前端
		res.send(Model)
	})

	//编辑分类
	router.put('/:id', async (req, res) => {
		// 填入put中传递过来的数据。
		const Model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
		// 将模型数据返回到前端
		res.send(Model)
	})

	router.get('/', async (req, res) => {
		const queryOptions = {}
		if (req.Model.modelName === 'Category') {
			queryOptions.populate = 'parent'
		}
		const items = await req.Model.find().setOptions(queryOptions).limit(10)
		res.send(items)
	})

	//七牛上传凭证	
	app.get('/admin/api/upload', (req, res, next) => {
		res.send({
			status: 1,
			message: '上传凭证获取成功',
			upToken: qnconfig.uploadToken,
		})
	})

	// 输出router对象，挂载在全局express上
	router.get('/:id', async (req, res) => {
		const Model = await req.Model.findById(req.params.id)
		res.send(Model)
	})

	app.get('/admin/api/add/:name',async(req, res) =>{
		const name = req.params.name
		const content = await Counter.findOneAndUpdate({"name":name},{$inc:{count:1}},{new:true})
		res.send({count:content.count})
	})

	app.get('/admin/api/minus/:name',async(req, res) =>{
		const name = req.params.name
		const content = await Counter.findOneAndUpdate({"name":name},{$inc:{count:-1}},{new:true})
		res.send({count:content.count})
	})

	//删除数据
	router.delete('/:id',async (req, res) => {
		// 填入传递过来的数据。
		await req.Model.findByIdAndDelete(req.params.id, req.body)
		// 将模型数据返回到前端
		res.send({
			success: true
		})
	})

	app.use('/admin/api/rest/:resource', async (req, res, next) => {
		//转化成单数大写的字符串形式
		const modelName = require('inflection').classify(req.params.resource)
		req.Model = require(`../../models/${modelName}`)
		
		next()
	}, router)

	/*const multer = require('multer')
	const upload = multer({dest: __dirname + '/../../upload'})
	app.post('/admin/api/upload', upload.single('file'), async (req, res) => {
		const file = req.file
		file.url = `http://localhost:3000/upload/${file.filename}`
		res.send(file)
	})
	
	const fileStorage = multer.diskStorage({
		//设置上传后文件路径，uploads文件夹需要手动创建！！！
	        destination: function (req, file, cb) {
			cb(null,  __dirname + '/../../upload/files')
		}, 
		//给上传文件重命名，获取添加后缀名
		filename: function (req, file, cb) {
			var fileFormat = (file.originalname).split(".");
			cb(null, file.originalname);
		}
	});
	
	const videoStorage = multer.diskStorage({
		//设置上传后文件路径，uploads文件夹需要手动创建！！！
	        destination: function (req, file, cb) {
			cb(null,  __dirname + '/../../upload/video')
		}, 
		//给上传文件重命名，获取添加后缀名
		filename: function (req, file, cb) {
			var fileFormat = (file.originalname).split(".");
			cb(null, file.originalname);
		}
	});
		//添加配置文件到muler对象。
	const files = multer({
			storage: fileStorage
		});
	const videos = multer({
			storage:videoStorage
		});
	
	app.post('/admin/api/upload/files', files.single('file'), async (req, res) => {
		const file = req.file
		file.url = `http://localhost:3000/upload/files/${file.filename}`
		res.send(file)
	})
	
	app.post('/admin/api/upload/video', videos.single('file'), async (req, res) => {
		const file = req.file
		file.url = `http://localhost:3000/upload/video/${file.filename}`
		res.send(file)
	})*/

	app.post('/admin/api/login',async (req,res)=>{
		const {username,password} = req.body
		//1.根据用户名查找用户
		const user = await AdminUser.findOne({username}).select('+password')
		assert(user, 422, '用户不存在！')
		//2.校验密码
		const isValid = bcrypt.compareSync(password,user.password)
		assert(isValid, 422, '密码错误！')
		//3.返回token和用户权限
		const token = jwt.sign({id:user._id},app.get('secret'))
		res.send({token,username,role:user.role,id:user.id,editor:user.editor})
	})
	
	//错误处理函数
	app.use(async (err, req, res, next)=>{
		res.status(err.statusCode || 500).send({
			message: err.message
		})
	})
}
